package com.sl.discovery.modular.registry;

import lombok.extern.slf4j.Slf4j;

import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.context.event.EventListener;
import org.springframework.util.Assert;

import java.util.HashMap;

@Slf4j
public class DbAutoServiceRegistration extends AbstractAutoServiceRegistration<Registration> {


    private DbRegistration registration;

    public DbAutoServiceRegistration(ServiceRegistry<Registration> serviceRegistry,
                                     AutoServiceRegistrationProperties autoServiceRegistrationProperties,
                                     DbRegistration registration) {
        super(serviceRegistry, autoServiceRegistrationProperties);
        this.registration = registration;
    }

    @Deprecated
    public void setPort(int port) {
        getPort().set(port);
    }

    @Override
    protected DbRegistration getRegistration() {
        if (this.registration.getPort() < 0 && this.getPort().get() > 0) {
            this.registration.setPort(this.getPort().get());
        }
        Assert.isTrue(this.registration.getPort() > 0, "service.port has not been set");
        return this.registration;
    }

    @Override
    protected DbRegistration getManagementRegistration() {
        return null;
    }

    @Override
    protected void register() {
//        if (!this.registration.getNacosDiscoveryProperties().isRegisterEnabled()) {
//            log.debug("Registration disabled.");
//            return;
//        }
        if (this.registration.getPort() < 0) {
            this.registration.setPort(getPort().get());
        }
        super.register();
    }

    @Override
    protected void registerManagement() {
//        if (!this.registration.getNacosDiscoveryProperties().isRegisterEnabled()) {
//            return;
//        }
        super.registerManagement();

    }

    @Override
    protected Object getConfiguration() {
        return new HashMap<>();
    }

    @Override
    protected boolean isEnabled() {
        return true;
    }

    @Override
    @SuppressWarnings("deprecation")
    protected String getAppName() {
        return super.getAppName();
//        return StringUtils.isEmpty(appName) ? super.getAppName() : appName;
    }
}
